package com.ruoyi.web.controller.app;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.app.api.PageEntity;
import com.ruoyi.web.controller.app.api.Result;
import com.ruoyi.web.controller.app.api.SysLoginModel;
import com.ruoyi.web.controller.app.util.JwtTokenUtil;
import com.ruoyi.web.controller.app.util.JwtUtil;
import com.ruoyi.web.controller.app.util.ZkUtils;
import io.swagger.annotations.Api;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;



@Controller
@Api(tags = "app", description = "APP接口")
@RequestMapping("/appWater")
public class AppWater {

    @Autowired
    private ISysUserService iUserService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IWaterUserService waterUserService;
    @Autowired
    private IWaterMeterService waterMeterService;
    @Autowired
    private IWaterMeterDatahistoryService userDataHisService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private IWaterMeterinstallinfoService iWaterMeterinstallinfoService;
    @Autowired
    private IWaterMeterrepairinfoService iWaterMeterrepairinfoService;
    @Autowired
    private IWaterWorkOrderService workOrderService;



    /**
     * app登录
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/mLogin", method = RequestMethod.POST)
    @ResponseBody
    public Result mLogin(@RequestBody SysLoginModel sysLoginModel) throws Exception {
        Result result;
        String username = sysLoginModel.getUsername();
        String password = sysLoginModel.getPassword();

        result = new Result<Object>();

        //1. 校验用户是否有效
        JSONObject obj = new JSONObject();
        SysUser user=new SysUser();

        String code="";
        String uuid="";
        String token1 = loginService.login(username, password, code,uuid);
        try
        {

            SysUser dto=iUserService.selectUserByName(username);
            if (dto == null){
                result.error500("查无此账号！");
                return result;
            }
            user.setUserName(username);
            user.setNickName(dto.getNickName());

            //用户登录信息
            obj.put("userInfo", user);

            // 生成token
            String token = JwtTokenUtil.sign(username, password);
            //token 信息
            obj.put("token", token);
            result.setResult(obj);
            result.setSuccess(true);
            result.setCode(200);
            return result;
        }
        catch (AuthenticationException e)
        {
            result.error500("用户名或密码错误");
            return result;
        }
    }

    /**
     * 获取用户信息
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    @ResponseBody
    public Map getUser(HttpServletRequest request) throws Exception {
        Result result;
        result = new Result<Object>();
        Map map=new HashMap();

        String username = JwtUtil.getUserNameByToken(request);

        if(!StringUtils.isEmpty(username)){
            SysUser dto=iUserService.selectUserByName(username);
            SysDept sysDept = deptService.selectDeptById(dto.getDeptId());
            map.put("devname",sysDept.getDeptName());
            map.put("userName",dto.getUserName());

        }
        return map;
    }

    /**
     * @功能：获取用户列表
     * @return
     */
    @GetMapping(value = "/userList")
    @ResponseBody
    public Result<PageEntity> userList(HttpServletRequest request,
                                       @RequestParam(name="userid") String userid,
                                       @RequestParam(name="username") String username,
                                       @RequestParam(name="useraddress") String useraddress,
                                       @RequestParam(name="meterNo") String meterNo,
                                       @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                       @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) throws Exception{

        String companyId="";
        String usernameZH = JwtUtil.getUserNameByToken(request);

        if(!StringUtils.isEmpty(usernameZH)){
            SysUser dto=iUserService.selectUserByName(usernameZH);
            companyId=dto.getDeptId().toString();
        }
        Result<PageEntity> result = new Result<PageEntity>();

        List<WaterUser> pageList = new ArrayList<WaterUser>();

        pageList = waterUserService.getWaterUserListPage(companyId,userid,username,useraddress,meterNo,(pageNo-1)*pageSize,pageSize);


        PageEntity entity=new PageEntity();
        entity.setRecords(pageList);
        entity.setTotal(pageList.size());
        result.setResult(entity);
        result.setSuccess(true);
        return result;
    }

    @GetMapping(value = "/getUserDataHislist")
    @ResponseBody
    public Result<PageEntity> getUserDataHislist(HttpServletRequest request,
                                       @RequestParam(name="userid") String userid,
                                       @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                       @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) throws Exception{


        Result<PageEntity> result = new Result<PageEntity>();

        List<WaterMeterDatahistory> pageList = new ArrayList<WaterMeterDatahistory>();

        pageList = userDataHisService.getUserDataHislist(userid,(pageNo-1)*pageSize,pageSize);


        PageEntity entity=new PageEntity();
        entity.setRecords(pageList);
        entity.setTotal(pageList.size());
        result.setResult(entity);
        result.setSuccess(true);
        return result;
    }

    /**
     * 新增燃具档案
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/userMeterDatahisAdd", method = RequestMethod.PUT)
    @ResponseBody
    public Result<WaterMeterDatahistory> userMeterDatahisAdd(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        Result<WaterMeterDatahistory> result = new Result<WaterMeterDatahistory>();
        WaterMeterDatahistory dto=new WaterMeterDatahistory();

        String userId = jsonObject.getString("userId");
        String userName = jsonObject.getString("userName");
        String meterNo = jsonObject.getString("meterNo");
        String cumulativeFlow = jsonObject.getString("cumulativeFlow");
        String pressure = jsonObject.getString("pressure");
        String flowRate = jsonObject.getString("flowRate");
        String flowVelocity = jsonObject.getString("flowVelocity");
        String remark =jsonObject.getString("remark");
        String picture =jsonObject.getString("checkpic");

        // 抄表时间
        String gastime = jsonObject.getString("gastime");
        String time = jsonObject.getString("time");

        String  readDate = gastime +" "+time;

        dto.setUserId(userId);
        dto.setMeterNo(meterNo);
        // dto.setCumulativeFlow(cumulativeFlow);
        dto.setPressure(pressure);
        dto.setFlowRate(flowRate);
        dto.setFlowVelocity(flowVelocity);
        dto.setRemark(remark);
        dto.setReadDate(readDate);
        dto.setPicture(picture);
        dto.setMeterType("1");
        try {
            String uName="";
            uName=JwtUtil.getUserNameByToken(request);
            if(!StringUtils.isEmpty(uName)){
                SysUser user=iUserService.selectUserByName(uName);
                dto.setCreateBy(user.getUserName());
                dto.setCreateTime(new Date());
                dto.setUpdateBy(user.getUserName());
                dto.setUpdateTime(new Date());
            }
        } catch (Exception e) {
            result.error500("操作失败!");
        }

        Integer add=userDataHisService.insertWaterMeterDatahistory(dto);

//        更新 最新抄表时间
        WaterMeter meter=new WaterMeter();
        meter.setMeterNo(meterNo);
        meter.setReadDate(readDate);
        waterMeterService.updateWaterMeterNo(meter);
        return result;
    }


    @PostMapping(value = "/upload")
    @ResponseBody
    public Result<?> upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Result<?> result = new Result<>();
        String savePath = "";
        String bizPath = request.getParameter("biz");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        String filePath = RuoYiConfig.getUploadPath();
        String ctxPath = filePath;
        bizPath= ZkUtils.getDateStrType();

        String fileName = FileUploadUtils.upload(filePath, file);

        System.out.println(fileName);
        if(fileName!=null){
            String url = serverConfig.getUrl() + fileName;
            result.setMessage(url);
            result.setSuccess(true);
        }else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        System.out.println(savePath);
        return result;
    }

    /**
     * @功能：获取用户报装列表
     * @return
     */
    @GetMapping(value = "/userMeterInstList")
    @ResponseBody
    public Result<PageEntity> userMeterInstList(HttpServletRequest request,
                                       @RequestParam(name="userid") String userid,
                                       @RequestParam(name="username") String username,
                                       @RequestParam(name="useraddress") String useraddress,
                                       @RequestParam(name="meterNo") String meterNo,
                                       @RequestParam(name="installState") String installState,
                                       @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                       @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) throws Exception{

        String companyId="";
        String uId="";
        String usernameZH = JwtUtil.getUserNameByToken(request);

        if(!StringUtils.isEmpty(usernameZH)){
            SysUser dto=iUserService.selectUserByName(usernameZH);
            companyId=dto.getDeptId().toString();
            uId=dto.getUserId().toString();
        }
        Result<PageEntity> result = new Result<PageEntity>();

        List<WaterMeterinstallinfo> pageList = new ArrayList<WaterMeterinstallinfo>();

        pageList = iWaterMeterinstallinfoService.getUserMeterInstListPage(companyId,uId,userid,installState,username,useraddress,meterNo,(pageNo-1)*pageSize,pageSize);


        PageEntity entity=new PageEntity();
        entity.setRecords(pageList);
        entity.setTotal(pageList.size());
        result.setResult(entity);
        result.setSuccess(true);
        return result;
    }

    /**
     * 报装提交
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/userMeterInstAdd", method = RequestMethod.PUT)
    @ResponseBody
    public Result<WaterMeterinstallinfo> userMeterInstAdd(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        Result<WaterMeterinstallinfo> result = new Result<WaterMeterinstallinfo>();
        WaterMeterinstallinfo dto=new WaterMeterinstallinfo();

        String orderNumber = jsonObject.getString("orderNumber");
        String meterNo = jsonObject.getString("meterNo");
        String installType = jsonObject.getString("installType");
        String installPlace = jsonObject.getString("installPlace");
        String installMore = jsonObject.getString("installMore");
        String pic =jsonObject.getString("checkpic");

        String gastime = jsonObject.getString("gastime");
        String time = jsonObject.getString("time");
        String readDate = gastime +" "+time;

        dto.setOrderNumber(orderNumber);
        dto.setInstallType(installType);
        dto.setInstallPlace(installPlace);
        dto.setInstallMore(installMore);
        dto.setPic(pic);
        dto.setInstallDate(readDate);
        dto.setInstallState("1");//已安装

        try {
            String uName="";
            uName=JwtUtil.getUserNameByToken(request);
            if(!StringUtils.isEmpty(uName)){
                SysUser user=iUserService.selectUserByName(uName);
                dto.setUpdateBy(user.getUserName());
                dto.setUpdateTime(new Date());
            }
        } catch (Exception e) {
            result.error500("操作失败!");
        }

        Integer add=iWaterMeterinstallinfoService.updateWaterMeterinstOrder(dto);

        //更新工单状态
        WaterWorkOrder order=new WaterWorkOrder();
        order.setOrderNumber(orderNumber);
        order.setStatus(Long.valueOf("3"));//在工单表里 刚改为 已完成 待审核
        workOrderService.updateWaterWorkOrderNumber(order);

        //更改表状态
        WaterMeter waterMeter=new WaterMeter();
        waterMeter.setMeterNo(meterNo);
        waterMeter.setMeterState(2);//更改为使用
        waterMeterService.updateWaterMeterNo(waterMeter);
        return result;
    }

    /**
     * @功能：获取用户维修列表
     * @return
     */
    @GetMapping(value = "/userMeterRepairtList")
    @ResponseBody
    public Result<PageEntity> userMeterRepairtList(HttpServletRequest request,
                                                   @RequestParam(name="userid") String userid,
                                                   @RequestParam(name="username") String username,
                                                   @RequestParam(name="useraddress") String useraddress,
                                                   @RequestParam(name="meterNo") String meterNo,
                                                   @RequestParam(name="installState") String installState,
                                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) throws Exception{

        String companyId="";
        String uId="";
        String usernameZH = JwtUtil.getUserNameByToken(request);

        if(!StringUtils.isEmpty(usernameZH)){
            SysUser dto=iUserService.selectUserByName(usernameZH);
            companyId=dto.getDeptId().toString();
            uId=dto.getUserId().toString();
        }
        Result<PageEntity> result = new Result<PageEntity>();

        List<WaterMeterrepairinfo> pageList = new ArrayList<WaterMeterrepairinfo>();

        pageList = iWaterMeterrepairinfoService.selectWaterMeterrepairinfoListPage(companyId,uId,userid,installState,username,useraddress,meterNo,(pageNo-1)*pageSize,pageSize);


        PageEntity entity=new PageEntity();
        entity.setRecords(pageList);
        entity.setTotal(pageList.size());
        result.setResult(entity);
        result.setSuccess(true);
        return result;
    }

    /**
     * 维修提交
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/userMeterRepairttAdd", method = RequestMethod.PUT)
    @ResponseBody
    public Result<WaterMeterrepairinfo> userMeterRepairttAdd(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        Result<WaterMeterrepairinfo> result = new Result<WaterMeterrepairinfo>();
        WaterMeterrepairinfo dto=new WaterMeterrepairinfo();

        String orderNumber = jsonObject.getString("orderNumber");
        String repairMore = jsonObject.getString("installMore");
        String pic =jsonObject.getString("checkpic");

        String gastime = jsonObject.getString("gastime");
        String time = jsonObject.getString("time");
        String readDate = gastime +" "+time;

        dto.setOrderNumber(orderNumber);
        dto.setRepairMore(repairMore);
        dto.setPic(pic);
        dto.setRepairState("1");//已维修
        dto.setRepairDate(readDate);

        try {
            String uName="";
            uName=JwtUtil.getUserNameByToken(request);
            if(!StringUtils.isEmpty(uName)){
                SysUser user=iUserService.selectUserByName(uName);
                dto.setUpdateBy(user.getUserName());
                dto.setUpdateTime(new Date());
            }
        } catch (Exception e) {
            result.error500("操作失败!");
        }

        Integer add=iWaterMeterrepairinfoService.updateWaterMeterrepairinfoNumber(dto);

        //更新工单状态
        WaterWorkOrder order=new WaterWorkOrder();
        order.setOrderNumber(orderNumber);
        order.setStatus(Long.valueOf("3"));//在工单表里 刚改为 已完成 待审核
        workOrderService.updateWaterWorkOrderNumber(order);

        return result;
    }

}
